package com.example.myapplication.part19;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.myapplication.R;

public class ImageViewActivity extends AppCompatActivity {

    private ImageView draggedView;
    private float downX, downY;
    private float initialX, initialY;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_view);

        @SuppressLint({"MissingInflatedId", "LocalSuppress"}) FrameLayout container = findViewById(R.id.container);

        ImageView image1 = findViewById(R.id.image1);
        ImageView image2 = findViewById(R.id.image2);

        setupDraggable(image1);
        setupDraggable(image2);
    }

    private void setupDraggable(final ImageView imageView) {
        imageView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                draggedView = (ImageView) v;
                initialX = v.getX();
                initialY = v.getY();
                downX = v.getX(); // 这里可能需要使用event.getRawX()？
                downY = v.getY();
                return true;
            }
        });
        imageView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (draggedView == v) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_MOVE:
                            float deltaX = event.getRawX() - downX;
                            float deltaY = event.getRawY() - downY;
                            float newX = initialX + deltaX;
                            float newY = initialY + deltaY;
                            draggedView.setX(newX);
                            draggedView.setY(newY);
                            break;
                        case MotionEvent.ACTION_UP:
                            draggedView = null;
                            break;
                    }
                    return true;
                }
                return false;
            }
        });
    }
}